/**
 * Copyright 2007 Jason Horman, Pete Aykroyd
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.functor;

import java.io.Serializable;

/**
 * A org.functor that takes two arguments and has no return value.
 */
public abstract class BinaryProcedure<Left,Right> implements Serializable {
	/**
	 * Execute this procedure.
	 *
	 * @param left  the first element of the ordered pair of arguments
	 * @param right the second element of the ordered pair of arguments
	 */
	public abstract void run(Left left, Right right);

	public static final BinaryProcedure NoOp = new BinaryProcedure() {
		public void run(Object left, Object right) {
		}
	};

	public Procedure bind(final Object left, final Object right) {
		final BinaryProcedure me = this;
		return new Procedure() {
			public void run() {
				me.run(left, right);
			}
		};
	}

	public UnaryProcedure bindLeft(final Object left) {
		final BinaryProcedure me = this;
		return new UnaryProcedure() {
			public void run(Object obj) {
				me.run(left, obj);
			}
		};
	}

	public UnaryProcedure bindRight(final Object right) {
		final BinaryProcedure me = this;
		return new UnaryProcedure() {
			public void run(Object obj) {
				me.run(obj, right);
			}
		};
	}

	/**
	 * When run executes the UnaryProcedure passed in with the right hand argument
	 * to the binary function.
	 */
	public static BinaryProcedure dropLeftAndExecute(final UnaryProcedure andExecute) {
		return new BinaryProcedure() {
			public void run(Object left, Object right) {
				andExecute.run(right);
			}
		};
	}

	/**
	 * When run executes the UnaryProcedure passed in with the left hand argument
	 * to the binary function.
	 */
	public static BinaryProcedure dropRightAndExecute(final UnaryProcedure andExecute) {
		return new BinaryProcedure() {
			public void run(Object left, Object right) {
				andExecute.run(left);
			}
		};
	}

	/**
	 * When run executes the Procedure passed with no arguments.
	 */
	public static BinaryProcedure dropAndExecute(final Procedure andExecute) {
		return new BinaryProcedure() {
			public void run(Object left, Object right) {
				andExecute.run();
			}
		};
	}

	public BinaryProcedure then(final BinaryProcedure doThis) {
		final BinaryProcedure me = this;
		return new BinaryProcedure() {
			public void run(Object left, Object right) {
				me.run(left, right);
				doThis.run(left, right);
			}
		};
	}
}
